<template>
  <div class="merchant-statistics">
    <h2 class="page-title">数据统计分析</h2>
    
    <!-- 日期筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据概览 -->

    
    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 各商品销量占比饼图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>各商品销量占比</span>
            <el-select v-model="foodSalesLimit" size="small" @change="updateFoodSalesChart">
              <el-option label="前5名" :value="5"></el-option>
              <el-option label="前10名" :value="10"></el-option>
              <el-option label="前15名" :value="15"></el-option>
            </el-select>
          </div>
          <div id="food-sales-chart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 订单状态分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单状态分布</span>
          </div>
          <div id="order-status-chart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <!-- 每日客流量统计 -->
      <el-col :span="24">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>每日活跃客户数</span>
          </div>
          <div id="customer-chart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 热销商品排行榜 -->
    <el-card class="table-card">
      <div slot="header" class="card-header">
        <span>热销商品排行榜</span>
      </div>
      <el-table
        :data="hotFoodsList"
        border
        stripe
        style="width: 100%">
        <el-table-column type="index" label="排名" width="80"></el-table-column>
        <el-table-column prop="foodId" label="商品ID" width="100"></el-table-column>
        <el-table-column prop="foodName" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="price" label="单价" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="salesCount" label="销量" width="100"></el-table-column>
        <el-table-column prop="salesAmount" label="销售额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.salesAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="销量占比" width="100">
          <template slot-scope="scope">
            {{ scope.row.percentage.toFixed(2) }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getMerchantStatistics,
  getMerchantOrderTrend,
  getMerchantFoodSalesProportion,
  getMerchantOrderStatusDistribution,
  getMerchantCustomerStatistics,
  getMerchantHotFoods
} from '@/api/merchant'

export default {
  name: 'MerchantStatistics',
  data() {
    return {
      // 过滤表单
      filterForm: {
        startDate: '',
        endDate: ''
      },
      
      // 日期范围
      dateRange: [],
      
      // 商家ID
      merchantId: null,
      
      // 统计数据
      statistics: {
        orderCount: 0,
        totalAmount: 0,
        completedCount: 0,
        cancelledCount: 0,
        averageAmount: 0
      },
      
      // 商品销量排行限制
      foodSalesLimit: 10,
      
      // 图表实例
      foodSalesChart: null,
      orderStatusChart: null,
      customerChart: null,
      
      // 热销商品列表
      hotFoodsList: []
    }
  },
  mounted() {
    this.getMerchantId()
    
    // 设置默认日期范围为过去7天
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 6)
    this.dateRange = [this.formatDate(start), this.formatDate(end)]
    this.filterForm.startDate = this.formatDate(start)
    this.filterForm.endDate = this.formatDate(end)
  },
  methods: {
    // 获取商家ID
    getMerchantId() {
      const userId = this.$store.state.user.id
      this.merchantId = this.$store.state.user.merchantId
      
      if (this.merchantId) {
        // 加载数据
        this.fetchStatisticsData()
        this.fetchHotFoods()
        
        // 初始化图表
        this.$nextTick(() => {
          this.initCharts()
        })
      }
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.filterForm.startDate = val[0]
        this.filterForm.endDate = val[1]
      } else {
        this.filterForm.startDate = ''
        this.filterForm.endDate = ''
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.fetchStatisticsData()
      this.fetchHotFoods()
      
      // 更新图表
      this.updateAllCharts()
    },
    
    // 重置筛选
    resetFilter() {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 6)
      
      this.dateRange = [this.formatDate(start), this.formatDate(end)]
      this.filterForm.startDate = this.formatDate(start)
      this.filterForm.endDate = this.formatDate(end)
      
      this.fetchStatisticsData()
      this.fetchHotFoods()
      
      // 更新图表
      this.updateAllCharts()
    },
    
    // 获取统计数据
    fetchStatisticsData() {
      getMerchantStatistics(
        this.merchantId, 
        this.filterForm.startDate, 
        this.filterForm.endDate
      )
        .then(response => {
          if (response.code === 200) {
            this.statistics = response.data
          } else {
            this.$message.error(response.message || '获取统计数据失败')
          }
        })
        .catch(error => {
          console.error('获取统计数据失败', error)
          this.$message.error('获取统计数据失败')
        })
    },
    
    // 获取热销商品
    fetchHotFoods() {
      getMerchantHotFoods(
        this.merchantId, 
        this.filterForm.startDate, 
        this.filterForm.endDate,
        20
      )
        .then(response => {
          if (response.code === 200) {
            this.hotFoodsList = response.data
          } else {
            this.$message.error(response.message || '获取热销商品失败')
          }
        })
        .catch(error => {
          console.error('获取热销商品失败', error)
          this.$message.error('获取热销商品失败')
        })
    },
    
    // 初始化所有图表
    initCharts() {
      this.initFoodSalesChart()
      this.initOrderStatusChart()
      this.initCustomerChart()
    },
    
    // 更新所有图表
    updateAllCharts() {
      this.updateFoodSalesChart()
      this.updateOrderStatusChart()
      this.updateCustomerChart()
    },
    
    // 初始化商品销量图表
    initFoodSalesChart() {
      this.foodSalesChart = echarts.init(document.getElementById('food-sales-chart'))
      this.updateFoodSalesChart()
      
      // 窗口大小变化时重绘图表
      window.addEventListener('resize', () => {
        this.foodSalesChart.resize()
      })
    },
    
    // 更新商品销量图表
    updateFoodSalesChart() {
      getMerchantFoodSalesProportion(
        this.merchantId, 
        this.filterForm.startDate, 
        this.filterForm.endDate,
        this.foodSalesLimit
      )
        .then(response => {
          if (response.code === 200) {
            const data = response.data
            
            // 准备图表数据
            const seriesData = data.map(item => {
              return {
                name: item.foodName,
                value: item.salesCount
              }
            })
            
            // 设置图表选项
            const option = {
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                data: data.map(item => item.foodName)
              },
              series: [
                {
                  name: '商品销量',
                  type: 'pie',
                  radius: ['50%', '70%'],
                  avoidLabelOverlap: false,
                  label: {
                    show: false,
                    position: 'center'
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: '16',
                      fontWeight: 'bold'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: seriesData
                }
              ]
            }
            
            this.foodSalesChart.setOption(option)
          } else {
            this.$message.error(response.message || '获取商品销量占比数据失败')
          }
        })
        .catch(error => {
          console.error('获取商品销量占比数据失败', error)
          this.$message.error('获取商品销量占比数据失败')
        })
    },
    
    // 初始化订单状态图表
    initOrderStatusChart() {
      this.orderStatusChart = echarts.init(document.getElementById('order-status-chart'))
      this.updateOrderStatusChart()
      
      // 窗口大小变化时重绘图表
      window.addEventListener('resize', () => {
        this.orderStatusChart.resize()
      })
    },
    
    // 更新订单状态图表
    updateOrderStatusChart() {
      getMerchantOrderStatusDistribution(
        this.merchantId, 
        this.filterForm.startDate, 
        this.filterForm.endDate
      )
        .then(response => {
          if (response.code === 200) {
            const data = response.data
            
            // 订单状态映射
            const statusMap = {
              1: '待付款',
              2: '待接单',
              3: '配送中',
              4: '已完成',
              5: '已取消'
            }
            
            // 准备图表数据
            const seriesData = Object.keys(data).map(key => {
              return {
                name: statusMap[key] || `状态${key}`,
                value: data[key]
              }
            })
            
            // 设置图表选项
            const option = {
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'vertical',
                left: 10,
                top: 'center',
                data: seriesData.map(item => item.name)
              },
              series: [
                {
                  name: '订单状态',
                  type: 'pie',
                  radius: ['50%', '70%'],
                  avoidLabelOverlap: false,
                  label: {
                    show: false,
                    position: 'center'
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: '16',
                      fontWeight: 'bold'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: seriesData
                }
              ]
            }
            
            this.orderStatusChart.setOption(option)
          } else {
            this.$message.error(response.message || '获取订单状态分布数据失败')
          }
        })
        .catch(error => {
          console.error('获取订单状态分布数据失败', error)
          this.$message.error('获取订单状态分布数据失败')
        })
    },
    
    // 初始化客户统计图表
    initCustomerChart() {
      this.customerChart = echarts.init(document.getElementById('customer-chart'))
      this.updateCustomerChart()
      
      // 窗口大小变化时重绘图表
      window.addEventListener('resize', () => {
        this.customerChart.resize()
      })
    },
    
    // 更新客户统计图表
    updateCustomerChart() {
      getMerchantCustomerStatistics(
        this.merchantId, 
        this.filterForm.startDate, 
        this.filterForm.endDate
      )
        .then(response => {
          if (response.code === 200) {
            const data = response.data
            
            // 准备图表数据
            const xAxisData = data.map(item => item.date)
            const customerData = data.map(item => item.customerCount)
            
            // 设置图表选项
            const option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                }
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                data: xAxisData
              },
              yAxis: {
                type: 'value',
                name: '客户数'
              },
              series: [
                {
                  name: '活跃客户数',
                  type: 'line',
                  data: customerData,
                  smooth: true,
                  areaStyle: {}
                }
              ]
            }
            
            this.customerChart.setOption(option)
          } else {
            this.$message.error(response.message || '获取客户统计数据失败')
          }
        })
        .catch(error => {
          console.error('获取客户统计数据失败', error)
          this.$message.error('获取客户统计数据失败')
        })
    }
  }
}
</script>

<style scoped>
.merchant-statistics {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-content {
  text-align: center;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #409EFF;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}
</style> 